﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;

namespace FileChat
{
    public partial class RegForm : Form
    {
        public RegForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 注册帐号 防止用户重名，造成信息混乱
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try {
                foreach (Control c in this.Controls) {
                    if (c is TextBox) {
                        if (c.Text == "") {
                            MessageBox.Show("为了便于沟通，所有内容都需要填写哟！");
                            return;
                        }
                    }
                }

                string fileChatPath = string.Format("{0}\\FileChatData.xml", txtFileChatPath.Text);
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fileChatPath);
                XmlNode root = xmlDoc.SelectSingleNode("FileChat/UserList");
                
                if (IsUserExist(root, txtUsername.Text)) {
                    MessageBox.Show("用户名被占用了，将使用其他的用户名");
                    return;
                }

                XmlElement user = xmlDoc.CreateElement("User");
                User u =new User();
                user.SetAttribute("ID", Guid.NewGuid().ToString());
                foreach (PropertyInfo pi in u.GetType().GetProperties()) {
                    try {
                        TextBox txt = this.Controls.Find(string.Format("txt{0}", pi.Name), false)[0] as TextBox;
                        user.SetAttribute(pi.Name, txt.Text);
                    }
                    catch(Exception ex){
                    
                    }
                
                }
                user.SetAttribute("Status", "offline");
                //密码采用MD5保存
                user.SetAttribute("Password",YiiUtil.MD5(txtPassword.Text));
                root.AppendChild(user);
                xmlDoc.Save(fileChatPath);

                MessageBox.Show("恭喜！您注册成功啦！");
                this.Close();

            }
            catch(Exception ex){
                MessageBox.Show("出错啦，请确认共享路径设置正确！");
                Console.Write(ex.Message);
            }
          
        }

        private Boolean IsUserExist(XmlNode root, string username) {
            foreach(XmlElement usernode in root.ChildNodes){
                if (usernode.Attributes["Username"].Value == username) {
                    return true;
                }
            }
            return false;
        }
    }
}
